<?php
!defined('DS') && define('DS', DIRECTORY_SEPARATOR);

$hackEncoding = '<?xml encoding="UTF-8">';
$funUrl       = 'https://www.php.net/manual/zh/indexes.functions.php'; // 函数
$reservedUrl  = 'https://www.php.net/manual/zh/reserved.variables.php'; // 预定义变量
$funs         = [];

$varKey = '<div id="reserved.variables"';
$funKey = '<div id="indexes.functions"';
$unKey  = '<section id="usernotes">';

function getFuns(&$funs, $url, $startKey, $endKey, $filterStr)
{
    $liReg = '/<li>(.*)<\/li>/isU';
    $aReg = '/<a href=\"(.*)?\"(.*)>(.*)<\/a>(.*)/is';
    var_dump(date('Y-m-d H:i:s') . ' getFuns url=' . $url. ' startKey=' . $startKey. ' endKey=' . $endKey. ' filterStr=' . $filterStr);
    $html_content = file_get_contents($url);
    var_dump(date('Y-m-d H:i:s') . ' getFuns html_content len=' . strlen($html_content));
    $idx1 = strpos($html_content, $startKey);
    $idx2 = strpos($html_content, $endKey);
    $html_content = substr($html_content, $idx1, $idx2 - $idx1);
    $html_content = str_replace('class="index"', '', $html_content);
    $html_contents = explode('</li>', $html_content);
    var_dump(date('Y-m-d H:i:s') . ' getFuns li len=' . count($html_contents));
    foreach ($html_contents as $html_content) {
        $html_content .= '</li>';
        preg_match_all($liReg, $html_content, $lines);
        if ($lines && $lines[0] && $lines[1]) {
            foreach ($lines[1] as $line) {
                if (strpos($line, $filterStr) === false) {
                    continue;
                }
                preg_match($aReg, $line, $a);
                if ($a && $a[1] && $a[3] && $a[4]) {
                    if (strpos($a[1], $filterStr) !== 0) {
                        continue;
                    }
                    $a[4] = str_replace("\n", "", $a[4]);
                    $fun = $a[3];
                    $idx = strtolower(substr($fun, 0, 1));
                    $inD = 0;
                    if ($idx == '$') {
                        $fun = ltrim($fun, '$');
                        $idx = strtolower(substr($fun, 0, 1));
                        $inD = 1;
                    }
                    $funs[$idx][$fun] = [
                        'url'  => $a[1],
                        'fun'  => $fun,
                        'desc' => $a[3] . $a[4],
                        'd'    => $inD,
                    ];
                }
            }
        }
    }
    var_dump(date('Y-m-d H:i:s') . ' getFuns funs len=' . count($funs));
}

getFuns($funs, $reservedUrl, $varKey, $unKey, 'reserved');
sleep(2);
getFuns($funs, $funUrl, $funKey, $unKey, 'function');
$str = json_encode($funs, 320);
$ret = file_put_contents(__DIR__ . '/functions.json', $str);
var_dump(date('Y-m-d H:i:s') . ' file_put_contents=' . $ret);exit;
// console.log(JSON.stringify(funs));
